<?php

class projectsListComponents extends myComponents
{
	static public $isActive = false;
	static public $sortable = array(
		'a-z'	=> 'name asc',
		'date'	=> 'created_at desc'
	);
	
	
	/**
	 * This method will be executed in order to activate
	 * the module itself
	 */
	public function executeInit()
	{
		self::$isActive = true;
		return sfView::NONE;
	}
	
	/**
	 * This method must NOT be executed before init
	 */
	public function executeRender()
	{
		$requestInstance = sfContext::getInstance()->getRequest();

		// Save current page to allow transparent navigation
		$this->getUser()->setAttribute('page',
			$requestInstance->getParameter('page', 1)
		);
		
		// Helper: how much we want to show per page
        sfContext::getInstance()->getConfiguration()->loadHelpers('Variable');
        
		// What kind of sorting user wants?
		if($requestInstance->getParameter('sort')) {
			$this->getUser()->setAttribute('sort', 
				$requestInstance->getParameter('sort')
			);
		}
		
		// Count of records
		$records = Doctrine::getTable('Product')->createQuery('p')
			->select('count(*)')
			->innerJoin('p.Translation pt')
			->where('pt.lang = ?', array($this->getUser()->getCulture()))
			->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
		
		// Getting list of the projects
		$this->projects = Doctrine::getTable('Product')->createQuery()
			->innerJoin('Product.Translation pt')
			->where('pt.lang = ?', array($this->getUser()->getCulture()));
		
			
		
		// Sorting ... ammmmm.
		if(isset(self::$sortable[$this->getUser()->getAttribute('sort')])) {
			$this->projects = $this->projects->orderBy(
				self::$sortable[$this->getUser()->getAttribute(('sort'))]
			);
		}
        
		// Used if sfView "projectsList::_render"
		$this->projects = $this->projects
			->offset(variable('per_page', 3) * (int)abs(($requestInstance->getParameter('page', 1) -1)))
			->limit(variable('per_page', 3))
			->execute();


        $this->links = LinkGen::getInstance(LinkGen::PRODUCT)->collectionLinks($this->projects);
        
        if(count($this->projects) >= 1) {
        	$this->page  = new AttitudePagination($requestInstance->getParameter('page', 1), ceil($records[0]['count'] / variable('per_page', 3)));
        }
	}
};